<template>
  <div flex-col>
    <!-- 搜索区域 -->

    <div h-75px bd-fff pt-30px pl-20px pr-20px mb-10px flex justify-between items-center>
      <div>
        <el-button
          v-hasPerm="['sys:dept:add']"
          plain
          text-15px
          type="primary"
          style="
            font-size: 15px;
            color: #fff;
            background: linear-gradient(
              90deg,
              rgba(0, 108, 222, 1) 0%,
              rgba(41, 182, 244, 1) 100%,
              rgba(0, 163, 235, 1) 99%
            );
            border: none;
          "
          @click="handleOpenDialog()"
        >
          新增部门
        </el-button>
        <el-button
          v-hasPerm="'sys:dept:delete'"
          type="danger"
          text-15px
          icon="delete"
          :disabled="selectIds.length === 0"
          @click="handleDelete()"
        >
          删除
        </el-button>
      </div>
      <div flex items-center flex-1 justify-end>
        <el-select
          v-model="queryParams.status"
          style="width: 100px; margin-right: 10px"
          placeholder="部门状态"
          clearable
        >
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <div mr--10px>
          <el-input
            v-model="queryParams.name"
            placeholder="部门名称"
            @keyup.enter="handleQuery"
          ></el-input>
        </div>
        <el-button type="primary" text-15px z-2 icon="search" @click="handleQuery">搜索</el-button>
        <el-button
          plain
          text-15px
          icon="refreshRight"
          style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
          @click="handleResetQuery"
        >
          清空
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="deptList"
      row-key="id"
      :border="false"
      stripe
      :header-cell-style="{
        backgroundColor: '#F1F3F7',
        color: '#000',
      }"
      highlight-current-row
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="部门名称" min-width="200" />
      <el-table-column prop="code" label="部门编号" width="200" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="sort" label="排序" width="100" />

      <el-table-column label="操作" fixed="right" align="left" width="200">
        <template #default="scope">
          <el-button
            v-hasPerm="['sys:dept:add']"
            type="primary"
            link
            size="small"
            icon="plus"
            @click.stop="handleOpenDialog(scope.row.id, undefined, undefined)"
          >
            新增
          </el-button>
          <el-button
            v-hasPerm="['sys:dept:edit']"
            type="primary"
            link
            size="small"
            icon="edit"
            @click.stop="handleOpenDialog(scope.row.parentId, scope.row.id, scope.row.leaderUserId)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPerm="['sys:dept:delete']"
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :show-close="false"
      :close-on-click-modal="false"
      width="900px"
      @closed="handleCloseDialog"
    >
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
        <!-- <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级部门"
            :data="deptOptions"
            :props="{ children: 'children', label: 'name', value: 'id' }"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item> -->
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入部门编号" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div pt-30px pb-40px flex justify-center>
          <el-button
            plain
            text-14px
            w-98px
            type="primary"
            style="
              font-size: 15px;
              color: #fff;
              background: linear-gradient(
                90deg,
                rgba(0, 108, 222, 1) 0%,
                rgba(41, 182, 244, 1) 100%,
                rgba(0, 163, 235, 1) 99%
              );
              border: none;
            "
            @click="handleSubmit"
          >
            提交
          </el-button>
          <el-button w-98px style="margin-left: 55px !important" plain @click="handleCloseDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

import DeptAPI, { DeptVO, DeptForm, DeptQuery } from "@/api/system/dept.api";

const deptFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<DeptQuery>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<DeptVO[]>();
// const deptOptions = ref<OptionType[]>();
const formData = reactive<DeptForm>({
  status: 1,
  parentId: "0",
  leaderUserId: "1001",
  sort: 1,
});

const rules = reactive({
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "部门编号不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 查询部门
function handleQuery() {
  loading.value = true;
  DeptAPI.getList(queryParams).then((data) => {
    deptList.value = data;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryParams.name = undefined;
  queryParams.status = undefined;
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开部门弹窗
 *
 * @param parentId 父部门ID
 * @param deptId 部门ID
 */
async function handleOpenDialog(parentId?: string, deptId?: string, leaderUserId?: string) {
  // 加载部门下拉数据
  // const data = await DeptAPI.getOptions();
  // deptOptions.value = [
  //   {
  //     id: "0",
  //     name: "顶级部门",
  //     leaderUserId: "1001",
  //     children: data,
  //   },
  // ];

  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改部门";
    DeptAPI.getFormData(deptId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增部门";
    formData.parentId = parentId || "0";
    formData.leaderUserId = leaderUserId || "1001";
  }
}

// 提交部门表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        DeptAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DeptAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除部门
function handleDelete(deptId?: number) {
  const deptIds = [deptId || selectIds.value].join(",");

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "确认信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showClose: false,
    confirmButtonClass: "message-box-confirm-button",
    cancelButtonClass: "message-box-cancel-button",
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.leaderUserId = "1001";
  formData.status = 1;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
